<template>
  <el-card style="max-width: 100%">
    <el-button
      style="margin-bottom: 20px"
      type="primary"
      size="default"
      icon="Plus"
      @click="addTm"
    >
      添加
    </el-button>
    <el-table class="tmTable tt" :data="trademarkArr" border>
      <el-table-column
        type="index"
        label="序号"
        width="80px"
        align="center"
      ></el-table-column>
      <el-table-column prop="title" label="名称" align="center">
        <template #default="{ row }">
          <pre>{{ row.title }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center">
        <template #="{ row }">
          <pre>{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="产品图片" align="center">
        <template #="{ row }">
          <!-- <img style="width: 50px;height: 50px;" :src="row.logoUrl" alt="" srcset=""> -->
          <el-image
            lazy
            style="width: 100px; height: 100px; position: relative; z-index: 1"
            :src="row.logoUrl"
            :zoom-rate="1.2"
            :preview-src-list="[row.logoUrl]"
            :min-scale="0.2"
            fit="cover"
            :preview-teleported="true"
          />
        </template>
      </el-table-column>
      <el-table-column>
        <template #="{ row, $index }">
          <el-row style="text-align: center">
            <el-col :span="12">
              <el-button
                size="large"
                type="warning"
                icon="Edit"
                @click="editTmData(row, $index)"
              />
            </el-col>
            <el-col :span="12">
              <el-button
                size="large"
                type="danger"
                icon="Delete"
                @click="deleteTmData(row, $index)"
              />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px"
      v-model:current-page="curPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 4]"
      :small="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      :background="true"
      @size-change="sizeChange"
      @current-change="currentChange"
      @prev-click="prevPage"
      @next-click="nextPage"
    />
  </el-card>

  <!-- 添加品牌：对话框 -->
  <el-dialog width="600" v-model="isDialog" title="添加品牌">
    <el-form :model="form" :rules="rules" ref="addTmForm">
      <el-form-item label="商品名称" label-width="140px" prop="title">
        <el-input v-model="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="品牌" label-width="140px" prop="tmName">
        <el-select-v2
          v-model="form.tmName"
          :options="options"
          :props="props"
          filterable
          placeholder="Please select"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="产品图片" label-width="140px" prop="fileUrl">
        <el-upload
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          list-type="picture-card"
          limit="1"
          :auto-upload="false"
          x
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.fileUrl"
            class="el-upload-list__item-thumbnail"
            :src="form.fileUrl"
            alt=""
          />
          <el-icon v-else>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isDialog = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { markRaw, onMounted, reactive, ref } from 'vue'
import { getTrademark } from '@/api/product/trademark/index.ts'
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

//当前页
let curPage = ref(1)
//每页显示条目个数
let pageSize = ref(3)
//总条数
let total = ref(0)
//已有品牌数组
let trademarkArr = ref<any>([])

//是否弹窗
let isDialog = ref(false)

//用于获取表单组件来验证
let addTmForm = ref()

//表单
let form = reactive({
  title: '',
  tmName: '',
  fileUrl: '', //添加品牌图片
})

//自定义配置
const props = {
  label: 'name',
  value: 'id',
}

/**
 *
 * @param _rule
 * @param value
 * @param callback
 */
const validateFileUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请将图片上传'))
  }
}

//验证规则，可自定义但此处没有自定义
const rules = reactive({
  title: [
    { required: true, message: '商品名称不可为空', trigger: 'blur' },
    { min: 2, max: 12, message: '长度为2~12', trigger: 'change' },
  ],
  tmName: [{ required: true, message: '品牌不可为空', trigger: 'change' }],
  fileUrl: [{ validator: validateFileUrl, trigger: 'change' }],
})

//模拟后端返回的mock选项数组
const options = [
  {
    id: 1,
    name: 'Brioni',
  },
  {
    id: 2,
    name: '花花公子',
  },
  {
    id: 3,
    name: '恒源',
  },
  {
    id: 4,
    name: '潮牌',
  },
  {
    id: 5,
    name: '乐町LEDIN',
  },
  {
    id: 6,
    name: '维莎曼VEROMODA',
  },
  {
    id: 7,
    name: '迪桑特DESCENTE',
  },
  {
    id: 8,
    name: '韩都衣舍',
  },
  {
    id: 9,
    name: 'PEACEBIRD太平鸟',
  },
  {
    id: 10,
    name: '美特斯邦威',
  },
  {
    id: 11,
    name: '柒牌SEVEN',
  },
]

/**
 * 获取品牌管理数据
 */
const getTrademarkData = async (curPage: number, pageSize: number) => {
  let result: any = await getTrademark(curPage, pageSize)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
  return result
}

/**
 * 组件挂载后
 */
onMounted(() => {
  getTrademarkData(curPage.value, pageSize.value)
})

/**
 * 上传文件之前触发的钩子：用于约束文件类型和大小等
 * @param rawFile 上传的文件
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //约束：文件类型：png|jpg|gif ，文件大小：5M
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('仅支持 png、jpg、gif 文件类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传文件的大小必须小于2M!')
    return false
  }
  return true
}

/**
 * page-size 改变时触发
 */
const sizeChange = (value: number) => {
  pageSize.value = value
  getTrademarkData(curPage.value, pageSize.value)
}

/**
 * current-page 改变时触发
 * @param value 跳转的页数
 */
const currentChange = (value: number) => {
  curPage.value = value
  getTrademarkData(curPage.value, pageSize.value)
}

const confirm = async () => {
  console.log(form)
  //表单数据验证
  await addTmForm.value.validate()
  //提交数据
  setTimeout(() => {
    isDialog.value = false
    ElMessage({
      message: '模拟添加成功',
      type: 'success',
    })
  }, 500)
}

const addTm = () => {
  isDialog.value = true
  form.title = ''
  form.tmName = ''
  form.fileUrl = ''
}

/**
 * 删除
 * @param row 某一项品牌数据
 * @param $index 索引
 */
const deleteTmData = (row: any, $index: any) => {
  ElMessageBox.confirm('确认删除吗?', '提示', {
    type: 'warning',
    icon: markRaw(Delete),
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(() => {
      try {
        trademarkArr.value.splice($index, 1)
        ElMessage({
          type: 'success',
          message: '模拟删除成功',
        })
      } catch (error) {
        ElMessage({
          type: 'error',
          message: '模拟删除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    })

  console.log(row, $index)
}

/**
 * 编辑
 * @param row 某一项品牌数据
 * @param $index 索引
 */
const editTmData = (row: any, $index: any) => {
  //将数据渲染到表单中

  //弹出对话框
  isDialog.value = true
  console.log(row, $index)
  form.title = row.title
  form.tmName = row.tmName
  form.fileUrl = row.logoUrl
}

/**
 * 上一页
 */
const prevPage = (value: number) => {
  console.log('上一页', value)
}

/**
 * 下一页
 */
const nextPage = (value: number) => {
  console.log('下一页', value)
}
</script>

<style scoped></style>
